package com.moss.web;

import com.github.pagehelper.PageInfo;
import com.moss.common.core.BaseController;
import com.moss.common.domain.AjaxResult;
import com.moss.common.entity.SysSampleEntity;
import com.moss.common.entity.SysSampleItemEntity;
import com.moss.common.entity.SysSamplerSignEntity;
import com.moss.common.exception.ServiceException;
import com.moss.common.util.IdUtil;
import com.moss.common.util.IncrCounter;
import com.moss.system.factory.SampleFactory;
import com.moss.system.service.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 采样管理
 */
@RestController
@RequestMapping("/sample")
public class SampleController extends BaseController {

    @Resource
    SampleService sampleService;

    @Resource
    SamplerSignService samplerSignService;

    @Resource
    SampleItemService sampleItemService;

    @Resource
    CompanyService companyService;

    @Resource
    SampleOrgService sampleOrgService;

    @Resource
    IncrCounter incrCounter;

    @Resource
    SampleFactory sampleFactory;


    @GetMapping("/list")
    public AjaxResult<List<SysSampleEntity>> list(SysSampleEntity sample){
        startPage();
        List<SysSampleEntity> list = sampleService.list(sample);
        return AjaxResult.success(list,new PageInfo<>(list).getTotal());
    }


    @GetMapping("/{sampleType}/randomSampleNo")
    public AjaxResult<String> randomSampleNo(@PathVariable String sampleType){
        return AjaxResult.success(incrCounter.randomSampleNo(sampleType));
    }

    @GetMapping("/listSampler")
    public AjaxResult<List<SysSamplerSignEntity>> listSampler(SysSamplerSignEntity sampler){
        return AjaxResult.success(samplerSignService.selectList(sampler));
    }

    @PostMapping("/saveSample")
    public AjaxResult<Void> saveSample(@RequestBody @Validated SysSampleEntity sample){
        sample.setCreateBy(getUserId());
        if (!companyService.checkCodeAndNameEq(sample.getUniformCode(),sample.getCompanyName())){
            throw new ServiceException("企业名称和信用代码不匹配，请检查");
        }
        if (sampleOrgService.checkCodeAndNameEq(sample.getSampleOrgCode(), sample.getSampleOrgName())) {
            throw new ServiceException("检测机构和机构编码不匹配，请检查");
        }
        this.handlerSampleItem(sample);
        String sampleId = IdUtil.randomUUID();
        sample.setSampleId(sampleId);
        SampleBranchService sampleBranchService = sampleFactory.create(sample.getSampleType());
        sampleBranchService.saveSample(sample);
        return AjaxResult.success();
    }

    public void handlerSampleItem(SysSampleEntity sample) {
        List<SysSampleItemEntity> itemList = sample.getItemList();
        String itemId = itemList.stream().map(SysSampleItemEntity::getItemId).collect(Collectors.joining(","));
        String itemName = itemList.stream().map(SysSampleItemEntity::getItemName).collect(Collectors.joining(","));
        sample.setItemId(itemId);
        sample.setItemName(itemName);
        itemList.forEach(o -> o.setSampleId(sample.getSampleId()));
    }

    @GetMapping("/{type}/{sampleId}")
    public AjaxResult<SysSampleEntity> getSample(@PathVariable String type,@PathVariable String sampleId){
        SampleBranchService sampleBranchService = sampleFactory.create(type);
        SysSampleEntity sample = sampleBranchService.getDetail(sampleId);
        List<SysSampleItemEntity> sampleItemList = sampleItemService.getSampleItem(sampleId);
        sample.setItemList(sampleItemList);
        return AjaxResult.success(sample);
    }


    @PostMapping("/updateSample")
    public AjaxResult<Void> updateSample(@RequestBody @Validated SysSampleEntity sample){
        sample.setUpdateBy(getUserId());
        if (sampleService.getSample(sample.getSampleId()).getStatus() == 1){
            throw new ServiceException("当前采样已录入检测，不允许修改");
        }
        if (!companyService.checkCodeAndNameEq(sample.getUniformCode(),sample.getCompanyName())){
            throw new ServiceException("企业名称和信用代码不匹配，请检查");
        }
        if (sampleOrgService.checkCodeAndNameEq(sample.getSampleOrgCode(), sample.getSampleOrgName())){
            throw new ServiceException("检测机构和机构编码不匹配，请检查");
        }
        sampleService.updateSample(sample);
        return AjaxResult.success();
    }


    @DeleteMapping("/{sampleIds}")
    public AjaxResult<Void> deleteSample(@PathVariable @NotNull(message = "请选中需要删除的数据") String[] sampleIds){
        if (sampleService.checkDelete(sampleIds)){
            throw new ServiceException("已录入的采样不允许删除，请确认");
        }
        sampleService.deleteSample(sampleIds);
        return AjaxResult.success();
    }

}
